package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {
    private Logger logger = Logger.getLogger(UserController.class);
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    private ArrayList<User> userList = new ArrayList<User>();
    private ArrayList<User> queryUserList = new ArrayList<User>();
    public UserController(){
        try {//初始化用户数据
            userList.add(new User(1,"test001","测试用户001","1111111",1,
                    new SimpleDateFormat("yyyy-MM-dd").parse("1986-12-10"),
                    "13566669998","北京市朝阳区北苑",1,1,new Date(),
                    1,new Date()));
            userList.add(new User(2,"zhaoyan","赵燕","2222222",1,
                    new SimpleDateFormat("yyyy-MM-dd").parse("1984-11-10"),
                    "18678786545","北京市海淀区成府路",1,1,new Date(),
                    1,new Date()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //没有查询条件的情况下，获取userList（公共查询）
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(Model model){
        logger.info("无条件查询下，获取userList（公共查询）=== userList");
        model.addAttribute("queryUserList",userList);
        return "user/userlist";
    }

    //添加查询条件：userName
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public String list(@RequestParam(value = "userName",required = false)String userName,Model model){
        logger.info("查询条件：userName：" + userName + "，获取userList===");
        if(userName != null && !userName.equals("")){
            for (User user:userList){
                if (user.getUserName().indexOf(userName) != -1){
                    queryUserList.add(user);
                }
            }
            model.addAttribute("queryUserList",queryUserList);
        }else{
            model.addAttribute("queryUserList",userList);
        }
        return "user/userlist";
    }

    @RequestMapping(value = "/add.html",method = RequestMethod.GET)
    public String add(@ModelAttribute("user") User user){
        return "user/useradd";
    }
    @RequestMapping(value = "/add.html",method = RequestMethod.POST)
    public String addSave(User user,HttpSession session){
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if(userService.add(user)){
            return  "redirect:/user/userlist.html";
        }
        return "useradd";
    }



    @RequestMapping(value = "/login.html")
    public String login(){
        logger.debug("UserController welcome SMBMS==================");
        return "login";
    }

    @RequestMapping(value = "/dologin.html",method = RequestMethod.POST)
    public String doLogin(@RequestParam String userCode,
                          @RequestParam String userPassword,
                          HttpSession session,
                          HttpServletRequest request){
        logger.debug("doLogin=============================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode);
        if (null != user){
            if(user.getUserPassword().equals(userPassword)){
                //登录成功
                //放入session
                session.setAttribute(Constants.USER_SESSION,user);
                //页面跳转(frame.jsp)
                return "redirect:/user/main.html";
                //response.sendRedirect("jsp/frame.jsp")
            }else{
                request.setAttribute("error","密码输入错误！");
                return "login";
            }
        }else {
            //页面跳转(login.jsp)带出提示信息——转发
            request.setAttribute("error","用户名不存在！");
            return "login";
        }
    }

    @RequestMapping(value = "/userlist.html")
    public String getUserList(Model model,
                              @RequestParam(value="queryname",required=false) String queryUserName,
                              @RequestParam(value="queryUserRole",required=false) String queryUserRole,
                              @RequestParam(value="pageIndex",required=false) String pageIndex){
        logger.info("getUserList ---- > queryUserName：" + queryUserName);
        logger.info("getUserList ---- > queryUserRole：" + queryUserRole);
        logger.info("getUserList ---- > pageIndex：" + pageIndex);
        int _queryUserRole = 0;
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;

        if(queryUserName == null){
            queryUserName = "";
        }
        if(queryUserRole != null && !queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }
        if(pageIndex != null){
            currentPageNo = Integer.valueOf(pageIndex);
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryUserName,_queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
        model.addAttribute("userList", userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "userlist";
    }

    @RequestMapping(value = "/useradd.html",method = RequestMethod.GET)
    public String addUser(@ModelAttribute("user") User user){
        return "useradd";
    }

    @RequestMapping(value = "/addsave.html",method = RequestMethod.POST)
    public String addUserSave(User user,
                              HttpSession session,
                              HttpServletRequest request,
                              @RequestParam(value = "attachs",required = false)MultipartFile[] attachs){
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        logger.info("uploadFile path ============== > "+path);
        for (int i = 0;i < attachs.length;i++){
            MultipartFile attach = attachs[i];
            if(!attach.isEmpty()){
                if(i==0){
                    errorInfo = "uploadFileError";
                }else if (i==1){
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件名后缀
                int filesize = 5000000;
                if (attach.getSize() > filesize){//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                }else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                    String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";
                    File targetFile = new File(path,fileName);
                    if (!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    }catch (Exception e){
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i==0){
                        idPicPath = path+File.separator+fileName;
                    }else if (i==1){
                        workPicPath = path+File.separator+fileName;
                    }
                    logger.debug("idPicPath：" + idPicPath);
                    logger.debug("workPicPath：" + workPicPath);
                }else{
                    request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag){
            user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
            user.setCreationDate(new Date());
            user.setIdPicPath(idPicPath);
            user.setWorkPicPath(workPicPath);
            if(userService.add(user)){
                return  "redirect:/user/userlist.html";
            }
        }
        return "useradd";
    }

    @RequestMapping(value="/ucexist.html")
    @ResponseBody
    public Object userCodeIsExit(@RequestParam String userCode) throws Exception {
        logger.debug("userCodeIsExit userCode===================== "+userCode);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            resultMap.put("userCode", "exist");
        }else{
            User user = userService.selectUserCodeExist(userCode);
            if(null != user)
                resultMap.put("userCode", "exist");
            else
                resultMap.put("userCode", "noexist");
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value = "/usermodify.html",method = RequestMethod.GET)
    public String getUserById(@RequestParam Integer uid,Model model){
        logger.debug("getUserById uid===================== "+uid);
        User user = userService.getUserById(uid);
        model.addAttribute(user);
        return "usermodify";
    }

    @RequestMapping(value = "/usermodifysave.html",method = RequestMethod.POST)
    public String modifyUserSave(User user,HttpSession session){
        logger.debug("modifyUserSave userid=========" + user.getId());
        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        if(userService.update(user)){
            return  "redirect:/user/userlist.html";
        }
        return "usermodify";
    }

    @RequestMapping(value = "/view",method = RequestMethod.GET)
    @ResponseBody
    public User view(@RequestParam Integer id){
        logger.debug("view id: " + id);
        User user = new User();
        try {
            user = userService.getUserById(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    @RequestMapping(value = "/pwdmodify.html")
    public String pwdModify(){
        return "pwdmodify";
    }

    @RequestMapping(value = "/pwdmodify",method = RequestMethod.GET)
    @ResponseBody
    public Object getPwdByUserId(@RequestParam String oldpassword,HttpSession session){
        Object o = (User)session.getAttribute(Constants.USER_SESSION);
        Map<String, String> resultMap = new HashMap<String, String>();
        if(null == o ){//session过期
            resultMap.put("result", "sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
            resultMap.put("result", "error");
        }else{
            String sessionPwd = ((User)o).getUserPassword();
            if(oldpassword.equals(sessionPwd)){
                resultMap.put("result", "true");
            }else{//旧密码输入不正确
                resultMap.put("result", "false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value = "/pwdsave.html",method = RequestMethod.POST)
    public String pwdSave(@RequestParam String newpassword,HttpSession session){
        Object o = (User)session.getAttribute(Constants.USER_SESSION);
        boolean flag = false;
        if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
            flag = userService.updatePwd(((User)o).getId(),newpassword);
            if(flag){
                return  "redirect:/user/login.html";
            }else{
                return "pwdmodify";
            }
        }else{
            return "pwdmodify";
        }
    }

    @RequestMapping(value = "/roleList",method = RequestMethod.GET)
    @ResponseBody
    public Object getRoleList(){
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        return JSONArray.toJSONString(roleList);
    }

    @RequestMapping(value = "/main.html")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/login.html";
        }
        return "frame";
    }

//    @RequestMapping(value = "exlogin.html",method = RequestMethod.GET)
//    public String exLogin(@RequestParam String userCode,@RequestParam String userPassword){
//        logger.debug("exlogin=============================================");
//        //调用service方法，进行用户匹配
//        User user = userService.login(userCode);
//        if (null == user){//登录失败
//            throw new RuntimeException("用户名或者密码不正确！");
//        }
//        return "redirect:/user/main.html";
//    }
//    @ExceptionHandler(value = {RuntimeException.class})
//    public String handlerException(RuntimeException e,HttpServletRequest req){
//        req.setAttribute("e",e);
//        return "error";
//    }

}
